package com.backend.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.backend.utils.JwtUtil;
import com.backend.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

//拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证 所有请求数据都包含在request中
        String token = request.getHeader("Authorization");
        try {
            //从redis获取到相同的token
            ValueOperations<String,String> ops = stringRedisTemplate.opsForValue();
            String redisToken = ops.get("token");
            if (redisToken == null) {
                //token已经失效
                throw new RuntimeException();
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //把业务数据存储进threadlocal
            ThreadLocalUtil.set(claims);
            //放行
            return true;
        }catch (Exception e){
            //http响应码是401
            response.setStatus(401);
            //不放行
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空threadlocal的数据
        ThreadLocalUtil.remove();
    }
}
